package maple.thelittleredbook.user.service;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import maple.thelittleredbook.common.dto.ApiResponse;

import maple.thelittleredbook.common.exception.BusinessException;
import maple.thelittleredbook.user.entity.User;
import maple.thelittleredbook.user.mapper.UserMapper;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Slf4j
@Service
public class RoleService {
    private final UserMapper userMapper;

    private static final Set<String> VALID_ROLES = Set.of("ADMIN", "USER");


    public RoleService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }


    public ResponseEntity<ApiResponse<Page<User>>> GetUsers(int pageSize, int pageNum) throws Exception {
        Page<User> page = new Page<>(pageNum, pageSize);
        userMapper.selectPage(page, null);
        return ResponseEntity.ok(ApiResponse.success(page));
    }

    public ResponseEntity<ApiResponse<String>> EnableAccount(Long userId) throws BusinessException {

        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", userId).set("is_active", 1);

        boolean success = userMapper.update(null, updateWrapper) > 0;

        if (!success) {
            throw new BusinessException("用户不存在或激活失败");
        }
        return ResponseEntity.ok(ApiResponse.success("success"));
    }

    public ResponseEntity<ApiResponse<String>> DisableAccount(Long userId) throws BusinessException {

        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", userId).set("is_active", 0);

        boolean success = userMapper.update(null, updateWrapper) > 0;

        if (!success) {
            throw new BusinessException("用户不存在或封禁失败");
        }

        return ResponseEntity.ok(ApiResponse.success("success"));
    }

    public ResponseEntity<ApiResponse<String>> UpdateAccountRole(Long userId, String newRole) throws BusinessException {

        if (!VALID_ROLES.contains(newRole)) {
            throw new BusinessException("非法Role类型,Role只被允许改成 \"ADMIN\", \"USER\"两种种");
        }

        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", userId).set("role", newRole);

        boolean success = userMapper.update(null, updateWrapper) > 0;

        if (!success) {
            throw new BusinessException("用户不存在或改变权限失败");
        }

        return ResponseEntity.ok(ApiResponse.success("success"));
    }

}
